package com.pai4j.message.factory;

import com.pai4j.message.core.sender.MessageSender;
import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * 消息发送器工厂
 * 管理和提供MessageSender实例
 *
 * @author PAI4J Team
 * @date 2025-11-01
 */
@Slf4j
public class MessageSenderFactory {

    /**
     * 发送器映射表
     * key: 渠道标识
     * value: 发送器列表（按优先级排序）
     */
    private static final Map<String, List<MessageSender>> SENDER_MAP = new ConcurrentHashMap<>();

    /**
     * 所有注册的发送器
     */
    private static final Map<String, MessageSender> ALL_SENDERS = new ConcurrentHashMap<>();

    /**
     * 默认发送器渠道
     */
    private static String defaultChannel = "message-queue";

    /**
     * 注册发送器
     */
    public static synchronized void register(MessageSender sender) {
        if (sender == null) {
            log.warn("尝试注册null MessageSender");
            return;
        }

        String channel = sender.getChannel();
        if (channel == null || channel.trim().isEmpty()) {
            log.warn("MessageSender的channel不能为空: {}", sender.getClass().getName());
            return;
        }

        String senderId = sender.getClass().getName();
        
        if (ALL_SENDERS.containsKey(senderId)) {
            log.debug("MessageSender已注册，跳过: {} for {}", senderId, channel);
            return;
        }

        ALL_SENDERS.put(senderId, sender);

        SENDER_MAP.compute(channel.toLowerCase(), (k, senders) -> {
            if (senders == null) {
                senders = new ArrayList<>();
            }
            senders.add(sender);
            senders.sort(Comparator.comparingInt(MessageSender::getPriority));
            return senders;
        });

        log.info("注册MessageSender成功: {} for {} (priority: {})", 
                senderId, channel, sender.getPriority());
    }

    /**
     * 获取指定渠道的发送器（优先级最高的）
     */
    public static MessageSender getSender(String channel) {
        if (channel == null || channel.trim().isEmpty()) {
            channel = defaultChannel;
        }

        List<MessageSender> senders = SENDER_MAP.get(channel.toLowerCase());
        if (senders != null && !senders.isEmpty()) {
            // 返回第一个可用的
            for (MessageSender sender : senders) {
                if (sender.isAvailable()) {
                    return sender;
                }
            }
        }

        log.warn("未找到可用的MessageSender: channel={}", channel);
        return null;
    }

    /**
     * 获取指定渠道的所有发送器
     */
    public static List<MessageSender> getSenders(String channel) {
        if (channel == null || channel.trim().isEmpty()) {
            return Collections.emptyList();
        }

        List<MessageSender> senders = SENDER_MAP.get(channel.toLowerCase());
        return senders != null ? new ArrayList<>(senders) : Collections.emptyList();
    }

    /**
     * 获取默认发送器
     */
    public static MessageSender getDefaultSender() {
        return getSender(defaultChannel);
    }

    /**
     * 设置默认渠道
     */
    public static void setDefaultChannel(String channel) {
        defaultChannel = channel;
        log.info("设置默认发送渠道: {}", channel);
    }

    /**
     * 判断是否支持指定渠道
     */
    public static boolean supports(String channel) {
        return getSender(channel) != null;
    }

    /**
     * 获取所有已注册的渠道
     */
    public static List<String> getAllChannels() {
        return SENDER_MAP.keySet().stream()
                .sorted()
                .collect(Collectors.toList());
    }

    /**
     * 获取所有已注册的发送器
     */
    public static List<MessageSender> getAllSenders() {
        return new ArrayList<>(ALL_SENDERS.values());
    }

    /**
     * 取消注册
     */
    public static synchronized void unregister(MessageSender sender) {
        if (sender == null) {
            return;
        }

        String senderId = sender.getClass().getName();
        ALL_SENDERS.remove(senderId);

        String channel = sender.getChannel();
        if (channel != null) {
            SENDER_MAP.computeIfPresent(channel.toLowerCase(), (k, senders) -> {
                senders.removeIf(s -> s.getClass().getName().equals(senderId));
                return senders.isEmpty() ? null : senders;
            });
            log.info("取消注册MessageSender: {} for {}", senderId, channel);
        }
    }

    /**
     * 清空所有注册
     */
    public static synchronized void clear() {
        ALL_SENDERS.clear();
        SENDER_MAP.clear();
        log.info("清空所有MessageSender注册");
    }

    /**
     * 获取注册统计信息
     */
    public static String getFactoryInfo() {
        StringBuilder info = new StringBuilder("MessageSenderFactory Info:\n");
        info.append("Total Senders: ").append(ALL_SENDERS.size()).append("\n");
        info.append("Supported Channels: ").append(SENDER_MAP.size()).append("\n");
        info.append("Default Channel: ").append(defaultChannel).append("\n");
        for (Map.Entry<String, List<MessageSender>> entry : SENDER_MAP.entrySet()) {
            info.append("  - ").append(entry.getKey()).append(": ")
                .append(entry.getValue().size()).append(" sender(s)\n");
        }
        return info.toString();
    }
}

